package org.ssm.demo.utils;

/**
 * @Author: Junerain
 * @Description:
 * @Date:Created in 17:44 2018/4/28
 * @Modified By:
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dom4j.xpath.DefaultXPath;
import org.ssm.demo.entity.User;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.ssm.demo.utils.IDnewUtils.getNumberForPK;

public class DomParserUtils {
    public static List<String> parseMethod1() throws DocumentException {
        List<String> result = new ArrayList<String>();

        SAXReader reader = new SAXReader();
        Document document = reader.read("D:\\Code\\workspace_intellij_ieda\\ssm\\xmlresource\\test1.xml");
        XPath xPath = new DefaultXPath("/resources/product[@name='QQ']/account[@id='987654321']/password");
        List<Element> list = xPath.selectNodes(document.getRootElement());
        for (Element element : list) {
            System.out.println(element.getTextTrim());
            result.add(element.getTextTrim());
        }
        return result;
    }

    public static List<String> parseMethod2() throws DocumentException {
        List<String> result = new ArrayList<String>();

        SAXReader reader = new SAXReader();
//        Document document = reader.read("E:\\IdeaProjects\\Example\\NetApp\\src\\main\\resources\\target.xml");
        Document document = reader.read("D:\\Code\\workspace_intellij_ieda\\ssm\\xmlresource\\test1.xml");
        List<Element> products = document.getRootElement().selectNodes("/resources/product");
        Iterator iterator = products.iterator();
        while (iterator.hasNext()) {
            Element product = (Element) iterator.next();
            String name = product.attributeValue("name");
            System.out.println(name);
        }
        return result;
    }

    public static void generate() {
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("resources");

        Element product = root.addElement("product");
        product.addAttribute("name", "QQ");

        Element account = product.addElement("account");
        account.addAttribute("id", "123456789");

        Element nickname = account.addElement("nickname");
        nickname.setText("QQ-account-1");

        Element password = account.addElement("password");
        password.setText("123asd21qda");

        Element level = account.addElement("level");
        level.setText("56");

        PrintWriter pWriter = null;
        XMLWriter xWriter = null;
        try {
            pWriter = new PrintWriter("D:\\Code\\workspace_intellij_ieda\\ssm\\xmlresource\\generate.xml");
            xWriter = new XMLWriter(pWriter);
            xWriter.write(doc);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                xWriter.flush();
                xWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //dom4j方式解析成xml文件
    public static String ExportXMLMethod(List<User> list,int title){
        String endContent = getNumberForPK();

        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
        String time = dateFormat.format(date);

        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("users");

        for(int i=0; i<list.size(); i++){
            Element id = root.addElement("id");
            id.addAttribute("id",list.get(i).getId().toString());

            Element username = id.addElement("username");
            username.addAttribute("username", list.get(i).getUserName());

            Element password = id.addElement("password");
            password.addAttribute("password", list.get(i).getPassword());

            Element age = id.addElement("age");
            age.addAttribute("age", list.get(i).getAge().toString());
        }

        PrintWriter pWriter = null;
        XMLWriter xWriter = null;
        String path = "D:\\\\Code\\\\workspace_intellij_ieda\\\\ssm\\\\xmlresource\\\\export_user_"+time+"_"+String.valueOf(title)+"_"+endContent+".xml";
        try {
//            pWriter = new PrintWriter("D:\\Code\\workspace_intellij_ieda\\ssm\\xmlresource\\export_user_"+time+"_"+String.valueOf(title)+"_"+endContent+".xml");
            pWriter = new PrintWriter(path);
            xWriter = new XMLWriter(pWriter);
            xWriter.write(doc);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                xWriter.flush();
                xWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;

    }

    //dom4j方式解析成xml文件
    public static String ExportXMLMethod1(List<String> list,int title){
        String endContent = getNumberForPK();

        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
        String time = dateFormat.format(date);

        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("users");

        for(int i=0; i<list.size(); i++){
            JSONObject jo = JSON.parseObject(list.get(i));

            Element id = root.addElement("id");
            id.addAttribute("id",jo.getString("id"));

            Element username = id.addElement("username");
            username.addAttribute("username", jo.getString("username"));

            Element password = id.addElement("password");
            password.addAttribute("password", jo.getString("password"));

            Element age = id.addElement("age");
            age.addAttribute("age", jo.getString("age"));
        }

        PrintWriter pWriter = null;
        XMLWriter xWriter = null;
        String path = "D:\\\\Code\\\\workspace_intellij_ieda\\\\ssm\\\\xmlresource\\\\export_user_"+time+"_"+String.valueOf(title)+"_"+endContent+".xml";
        try {
//            pWriter = new PrintWriter("D:\\Code\\workspace_intellij_ieda\\ssm\\xmlresource\\export_user_"+time+"_"+String.valueOf(title)+"_"+endContent+".xml");
            pWriter = new PrintWriter(path);
            xWriter = new XMLWriter(pWriter);
            xWriter.write(doc);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                xWriter.flush();
                xWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;

    }

    //输入xml文件路径的集合，合并成一个完整的文件
    public static void getOneXML(Map<Integer,String> map){
        SAXReader saxReader = new SAXReader();
        Document main = null;
        try {
            main = saxReader.read(new File(map.get(0)));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element parent = (Element) main.getRootElement();//获得第一个xml的根节点

        Document b = null;
        for(int i = 0;i<map.size()-1;i++){
            try {
                b = saxReader.read(new File(map.get(i+1)));
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            List<Element> elements = b.getDocument().getRootElement().elements();//获得根节点下的节点信息

            for (Element element : elements) {
                parent.add(element.detach());//将b下的节点添加到a的根节点下
            }
        }
//        System.out.println(main.asXML());

        //输出为文件
        PrintWriter pWriter = null;
        XMLWriter xWriter = null;
        try {
            pWriter = new PrintWriter("D:\\Code\\workspace_intellij_ieda\\ssm\\xmlresource\\export_user_whole.xml");
            xWriter = new XMLWriter(pWriter);
            xWriter.write(main);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                xWriter.flush();
                xWriter.close();
                //删除不需要的部分文件
                for(int i=0;i<map.size();i++){
                    deletefile(map.get(i));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //根据目录删除文件
    public static boolean deletefile(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            System.out.println("删除文件失败:" + fileName + "不存在！");
            return false;
        } else {
            if (file.isFile()) {
                file.delete();
                return true;
            }else {
                System.out.println("删除文件失败:" + fileName + "不是一个文件！");
                return false;
            }
        }
    }


}
